<template>
	<view class="restaurant-edit-categories-container">
		<common-title :title="titleContent" @clickLeft="backToUpPage"></common-title>
		<view class="restaurant-edit-category-form">
			<uni-forms ref="editCategoryForm" :modelValue="editCategoryFormData" :rules="editCategoryFromRules">
				<!-- 类别名：categoryName -->
				<uni-forms-item label="类别名" required name="categoryName">
					<uni-easyinput v-model="editCategoryFormData.categoryName" placeholder="请输入菜名"></uni-easyinput>
				</uni-forms-item>
				<!-- 是否上架：status -->
				<uni-forms-item label="状态" name="staus" required>
					<uni-data-checkbox v-model="editCategoryFormData.status" :localdata="categoryStatus"></uni-data-checkbox>
				</uni-forms-item>
				<!-- 类别排序：sort -->
				<uni-forms-item label="菜品类别" name="sort" required>
					<uni-data-select
					      v-model="editCategoryFormData.sort"
					      :localdata="sort"
						  placeholder="请选择 (数字越小，优先级越高)"
					/>
				</uni-forms-item>
			</uni-forms>
			
			<!-- 底部操纵按钮 -->
			<view class="buttonOption">
			    <view 
			        class="editCategoryButton" 
			        @click="submit" 
			        :class="{'active': isPressedEdit}" 
			        @touchstart="onPressEdit" 
			        @touchend="onReleaseEdit">
			        修改菜品类别
			    </view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, onMounted } from "vue";
	import { useRoute } from "vue-router"; // 使用 vue-router 来获取路由参数
	import { apiGetRestaurantCatetoryInfoByCategoryName, apiPutRestaurantCategory } from "@/utils/apiRestaurant.js"
	//================================common-title=========================================
	//标题内容
	const titleContent = ref({
		left:'返回',
		midst:'餐厅-修改菜品类别'
	});
	
	//返回
	const backToUpPage = () => {
		if (fromPage.value === 'available') {
			uni.redirectTo({
				url:'/pages/manage/restaurant_manage/restaurant-available-categories'
			})
		} else if(fromPage.value === 'removed') {
			uni.redirectTo({
				url:'/pages/manage/restaurant_manage/restaurant-removed-categories'
			})
		}
	};
	//================================uni-form=========================================
	// 表单引用
	const editCategoryForm = ref(null);
	
	// 表单数据
	// 定义初始状态
	const initialFormData = {
	    categoryName: '',
	    sort: null,
	    status: null
	};
	
	// 创建 ref 对象
	const editCategoryFormData = ref({ ...initialFormData });
	// 承接旧值
	const editCategoryFormDataOld = ref({ ...initialFormData });
	// 表单验证规则
	const editCategoryFromRules = {
		categoryName: {
			rules: [
				{
					required: true,
					errorMessage: '类别名不能为空'
				},
				{
					minLength: 1,
					maxLength: 6,
					errorMessage: '类别名长度在 {minLength} 到 {maxLength} 个字符',
					validateFunction(rule, value, data, callback) {
						// 正则表达式定义为字符串
						const pricePattern = new RegExp('^(?=[^_])[\\u4e00-\\u9fa5A-Za-z0-9_]+$');
						
						if (!pricePattern.test(value)) {
							callback('只能是中文，字母，数字，下划线，且不能下划线开头');
						} else {
							callback(); // 校验通过
						}
					}
				}
			]
		},
		sort: {
			rules: [
				{
					required: true,
					errorMessage: '请选择类别'
				}
			]
		},
		status: {
			rules: [
				{
					required: true,
					errorMessage: '类别状态不能为空'
				}
			]
		}
	}
	
	//菜品类别状态
	const categoryStatus = ref([
		{text: '上架',value: 1}, 
		{text: '下架',value: 0}
	]);
	//类别排序
	const sort = ref([
		{text: '1',value: 1},
		{text: '2',value: 2},
		{text: '3',value: 3},
		{text: '4',value: 4},
		{text: '5',value: 5},
		{text: '6',value: 6},
		{text: '7',value: 7},
		{text: '8',value: 8},
		{text: '9',value: 9}
	]);
	
	
	const fromPage = ref(null);
	
	// onMounted 生命周期钩子，获取菜品类别信息
	onMounted(async () => {
	    const route = useRoute(); // 获取路由实例
	    const categoryName = route.query.categoryName; // 从路由查询参数中获取 id
		const from = route.query.from;
		// console.log(from);
		// console.log(categoryName);
		fromPage.value = from;
		editCategoryForm.value.setRules(editCategoryFromRules);
		
		let result = await apiGetRestaurantCatetoryInfoByCategoryName(categoryName);
		// console.log(result);
		editCategoryFormData.value = result;
		editCategoryFormDataOld.value = JSON.parse(JSON.stringify(result));
		// console.log(editCategoryFormData);
		
		
	    // 调用 API 获取菜品类别信息
	   
	});
	
	
	//=======================底部按钮=======================================
	
	const isPressedEdit = ref(false);
	//点击新增按钮
	const onPressEdit = () => {
		isPressedEdit.value = true;
	};
	
	//长按新增按钮
	const onReleaseEdit = () => {
		isPressedEdit.value = false;
	};
	
	// 提交修改
	let isSubmitting = false; // 标志变量，初始化为 false
	
	const submit = async () => {
		if (isSubmitting) return; // 如果正在提交，则直接返回
			
		isSubmitting = true; // 设置为正在提交状态
		
		let isEqual = JSON.stringify(editCategoryFormData.value) === JSON.stringify(editCategoryFormDataOld.value);
		if (isEqual) {
			uni.showToast({
				title:"无改动",
				icon:'none'
			});
			isSubmitting = false; // 重置提交状态
		}else {
			try {
			    // 等待表单验证的结果
			    await editCategoryForm.value.validate();
				// 创建 FormData 实例
				const formData = new FormData();
				// 将表单数据添加到 FormData
				for (const key in editCategoryFormData.value) {
					formData.append(key, editCategoryFormData.value[key]);
				}

				// 用户确认修改
				const res = await uni.showModal({
					title: '提示',
					content: '是否确认修改？'
				});
				if (res.confirm) { // 检查用户是否点击了“确认”
					const response = await apiPutRestaurantCategory(formData); // 等待 API 返回
		
					if (response === '200') { // 假设 response 包含 status 属性
						uni.showToast({
							title: "修改菜品类别成功",
							icon: 'success'
						});
						if (fromPage.value === 'available') {
							uni.redirectTo({
								url:'/pages/manage/restaurant_manage/restaurant-available-categories'
							})
						} else if(fromPage.value === 'removed') {
							uni.redirectTo({
								url:'/pages/manage/restaurant_manage/restaurant-removed-categories'
							})
						}
					} else {
						uni.showToast({
							title: "修改失败，请稍后再试",
							icon: 'none'
						});
					}
				}
				
			} catch (err) {
			    console.log('表单错误信息：', err); // 捕获验证和 API 调用中的错误
			} finally {
				// TODO: 提交后清除表单信息等操作
			    
				isSubmitting = false; // 重置提交状态
				
				
			}
		}
	};
	
</script>

<style lang="scss" scoped>
	.restaurant-edit-categories-container{
		.restaurant-edit-category-form{
			padding: 30rpx;
		}
		.buttonOption{
			position: absolute;
			width: 670rpx;
			display: flex;
			align-items: center;
			justify-content: space-around;
			bottom: 50rpx;
			
			font-weight: bold;
			font-size: 36rpx;
			color: #000000 ;
			padding: 30rpx;
			.editCategoryButton{
				width: 400rpx;
				height: 120rpx;
				border-radius: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: $brand-theme-color;
				box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			}
			.editCategoryButton.active {
			    background-color: #e4e4e4; /* 按下时的背景色 */
			    color: #999; /* 按下时的文字颜色 */
			}
		}
	}
</style>